package com.lucifer.treasure.enchant.effect;

import com.lucifer.treasure.util.SwordAuraLogger;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.server.world.ServerWorld;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.List;
import java.util.ArrayList;

/**
 * 御剑术PVP系统 - 独立管理所有PVP相关逻辑
 */
public class SwordAuraPvPSystem {
    
    // PVP攻击频率控制
    private static final Map<UUID, Long> PVP_ATTACK_COOLDOWN = new ConcurrentHashMap<>(); // 玩家PVP攻击冷却
    private static final Map<UUID, Integer> PVP_ATTACK_COUNT = new ConcurrentHashMap<>(); // 玩家PVP攻击次数
    private static final Map<UUID, Long> PVP_RESET_TIME = new ConcurrentHashMap<>(); // 重置时间
    
    // PVP敌对关系管理
    private static final Map<String, Long> PVP_HOSTILITY_CACHE = new ConcurrentHashMap<>(); // key: "playerId1_playerId2", value: 敌对关系结束时间
    
    // PVP配置常量
    private static final int MAX_PVP_ATTACKS = 10; // 30秒内最多10次PVP攻击
    private static final int PVP_ATTACK_INTERVAL = 2 * 20; // 2秒PVP攻击间隔
    private static final int PVP_RESET_INTERVAL = 30 * 20; // 30秒重置间隔
    private static final int PVP_HOSTILITY_DURATION = 60 * 20; // 敌对关系持续60秒
    
    /**
     * 检查是否允许PVP攻击
     */
    public static boolean isPvPAttackAllowed(PlayerEntity attacker, LivingEntity target, ServerWorld world) {
        if (!(target instanceof PlayerEntity)) {
            return true; // 对怪物攻击不受PVP限制
        }
        
        PlayerEntity targetPlayer = (PlayerEntity) target;
        UUID attackerId = attacker.getUuid();
        long currentTime = world.getTime();
        
        // 检查基本PVP有效性
        if (!isValidPvPTarget(targetPlayer, attacker)) {
            return false;
        }
        
        // 检查2秒攻击间隔
        Long lastAttackTime = PVP_ATTACK_COOLDOWN.get(attackerId);
        if (lastAttackTime != null && (currentTime - lastAttackTime) < PVP_ATTACK_INTERVAL) {
            return false; // 还在冷却中
        }
        
        // 检查30秒内攻击次数限制
        resetPvPCountersIfNeeded(attackerId, currentTime);
        int attackCount = PVP_ATTACK_COUNT.getOrDefault(attackerId, 0);
        if (attackCount >= MAX_PVP_ATTACKS) {
            return false; // 达到次数限制
        }
        
        return true;
    }
    
    /**
     * 记录PVP攻击
     */
    public static void recordPvPAttack(PlayerEntity attacker, LivingEntity target, ServerWorld world) {
        if (!(target instanceof PlayerEntity)) {
            return; // 对怪物攻击不记录
        }
        
        UUID attackerId = attacker.getUuid();
        long currentTime = world.getTime();
        
        // 更新攻击冷却
        PVP_ATTACK_COOLDOWN.put(attackerId, currentTime);
        
        // 更新攻击次数
        resetPvPCountersIfNeeded(attackerId, currentTime);
        int newCount = PVP_ATTACK_COUNT.getOrDefault(attackerId, 0) + 1;
        PVP_ATTACK_COUNT.put(attackerId, newCount);
        
        // 记录日志
        String attackerName = SwordAuraLogger.getPlayerName(attacker);
        String targetName = SwordAuraLogger.getPlayerName((PlayerEntity) target);
        SwordAuraLogger.log(SwordAuraLogger.LogLevel.INFO, SwordAuraLogger.Category.ATTACK,
                String.format("[%s] PVP攻击记录 -> %s (第%d次/10次)", attackerName, targetName, newCount));
    }
    
    /**
     * 检查是否有活跃的敌对关系
     */
    public static boolean hasActiveHostility(PlayerEntity player1, PlayerEntity player2) {
        if (!isValidPvPTarget(player2, player1)) {
            return false;
        }
        
        long currentTime = player1.getWorld().getTime();
        String hostilityKey1 = player1.getUuid().toString() + "_" + player2.getUuid().toString();
        String hostilityKey2 = player2.getUuid().toString() + "_" + player1.getUuid().toString();
        
        // 检查双向敌对关系
        Long hostilityEnd1 = PVP_HOSTILITY_CACHE.get(hostilityKey1);
        Long hostilityEnd2 = PVP_HOSTILITY_CACHE.get(hostilityKey2);
        
        return (hostilityEnd1 != null && currentTime < hostilityEnd1) || 
               (hostilityEnd2 != null && currentTime < hostilityEnd2);
    }
    
    /**
     * 建立敌对关系
     */
    public static void establishHostility(PlayerEntity attacker, PlayerEntity target, ServerWorld world) {
        if (!isValidPvPTarget(target, attacker)) {
            return;
        }
        
        long currentTime = world.getTime();
        long hostilityEndTime = currentTime + PVP_HOSTILITY_DURATION;
        
        // 建立双向敌对关系
        String hostilityKey1 = attacker.getUuid().toString() + "_" + target.getUuid().toString();
        String hostilityKey2 = target.getUuid().toString() + "_" + attacker.getUuid().toString();
        
        PVP_HOSTILITY_CACHE.put(hostilityKey1, hostilityEndTime);
        PVP_HOSTILITY_CACHE.put(hostilityKey2, hostilityEndTime);
        
        // 记录日志
        String attackerName = SwordAuraLogger.getPlayerName(attacker);
        String targetName = SwordAuraLogger.getPlayerName(target);
        SwordAuraLogger.log(SwordAuraLogger.LogLevel.INFO, SwordAuraLogger.Category.ATTACK,
                String.format("🔥 [%s] 建立敌对关系 -> %s (60秒)", attackerName, targetName));
    }
    
    /**
     * 清理指定玩家的所有敌对关系
     */
    public static int clearAllPlayerHostilities(UUID playerId) {
        String playerIdStr = playerId.toString();
        int clearedCount = 0;
        
        // 清理所有包含该玩家ID的敌对关系
        List<String> toRemove = new ArrayList<>();
        for (String key : PVP_HOSTILITY_CACHE.keySet()) {
            if (key.contains(playerIdStr)) {
                toRemove.add(key);
            }
        }
        
        for (String key : toRemove) {
            PVP_HOSTILITY_CACHE.remove(key);
            clearedCount++;
        }
        
        return clearedCount;
    }
    
    /**
     * 获取玩家的敌对关系信息 - 只返回单向关系，避免UI重复显示
     */
    public static List<HostilityInfo> getPlayerHostilities(PlayerEntity player) {
        List<HostilityInfo> hostilities = new ArrayList<>();
        long currentTime = player.getWorld().getTime();
        
        // 清理过期的敌对关系
        cleanupExpiredHostility(currentTime);
        
        String playerIdStr = player.getUuid().toString();
        java.util.Set<String> processedPlayers = new java.util.HashSet<>(); // 避免重复显示
        
        for (Map.Entry<String, Long> entry : PVP_HOSTILITY_CACHE.entrySet()) {
            String key = entry.getKey();
            long endTime = entry.getValue();
            
            if (currentTime >= endTime) {
                continue; // 已过期
            }
            
            String otherPlayerId = null;
            
            // 检查是否与当前玩家相关
            if (key.startsWith(playerIdStr + "_")) {
                // 我攻击的敌对关系
                otherPlayerId = key.substring(playerIdStr.length() + 1);
            } else if (key.endsWith("_" + playerIdStr)) {
                // 攻击我的敌对关系
                otherPlayerId = key.substring(0, key.length() - playerIdStr.length() - 1);
            }
            
            // 如果找到了相关的敌对关系，且还没有处理过这个玩家
            if (otherPlayerId != null && !processedPlayers.contains(otherPlayerId)) {
                String targetName = getPlayerNameById(otherPlayerId, player.getWorld());
                if (targetName != null) {
                    hostilities.add(new HostilityInfo(targetName, endTime - currentTime, true)); // 统一显示为敌对关系
                    processedPlayers.add(otherPlayerId);
                }
            }
        }
        
        return hostilities;
    }
    
    /**
     * 重置PVP计数器（如果需要）
     */
    private static void resetPvPCountersIfNeeded(UUID playerId, long currentTime) {
        Long lastResetTime = PVP_RESET_TIME.get(playerId);
        if (lastResetTime == null || (currentTime - lastResetTime) >= PVP_RESET_INTERVAL) {
            PVP_ATTACK_COUNT.put(playerId, 0);
            PVP_RESET_TIME.put(playerId, currentTime);
        }
    }
    
    /**
     * 清理过期的敌对关系
     */
    private static void cleanupExpiredHostility(long currentTime) {
        List<String> toRemove = new ArrayList<>();
        for (Map.Entry<String, Long> entry : PVP_HOSTILITY_CACHE.entrySet()) {
            if (currentTime >= entry.getValue()) {
                toRemove.add(entry.getKey());
            }
        }
        
        for (String key : toRemove) {
            PVP_HOSTILITY_CACHE.remove(key);
        }
    }
    
    /**
     * 检查是否是有效的PVP目标
     */
    private static boolean isValidPvPTarget(LivingEntity entity, PlayerEntity attacker) {
        if (!(entity instanceof PlayerEntity)) {
            return false;
        }
        
        PlayerEntity target = (PlayerEntity) entity;
        
        // 不能攻击自己
        if (target.getUuid().equals(attacker.getUuid())) {
            return false;
        }
        
        // 检查玩家是否在创造模式或观察者模式
        if (target.isCreative() || target.isSpectator()) {
            return false;
        }
        
        // TODO: 可以添加更多PVP限制条件，如：
        // - 保护区域检查
        // - 队伍系统检查
        // - 等级差距检查
        
        return true;
    }
    
    /**
     * 根据玩家ID获取玩家名称
     */
    private static String getPlayerNameById(String playerId, net.minecraft.world.World world) {
        try {
            UUID uuid = UUID.fromString(playerId);
            PlayerEntity player = world.getPlayerByUuid(uuid);
            return player != null ? player.getName().getString() : null;
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 敌对关系信息类
     */
    public static class HostilityInfo {
        public final String playerName;
        public final long remainingTicks;
        public final boolean isOutgoing; // 保留用于兼容性，现在统一为true
        
        public HostilityInfo(String playerName, long remainingTicks, boolean isOutgoing) {
            this.playerName = playerName;
            this.remainingTicks = remainingTicks;
            this.isOutgoing = isOutgoing;
        }
        
        public int getRemainingSeconds() {
            return (int) (remainingTicks / 20);
        }
        
        public float getProgressPercent() {
            return (float) remainingTicks / PVP_HOSTILITY_DURATION;
        }
    }
    
    /**
     * 清理玩家数据
     */
    public static void cleanupPlayerData(UUID playerId) {
        PVP_ATTACK_COOLDOWN.remove(playerId);
        PVP_ATTACK_COUNT.remove(playerId);
        PVP_RESET_TIME.remove(playerId);
        clearAllPlayerHostilities(playerId);
    }
    
    /**
     * 测试功能：添加假敌对关系
     */
    public static void addTestHostility(PlayerEntity player, String fakePlayerName, boolean isOutgoing, int remainingSeconds) {
        long currentTime = player.getWorld().getTime();
        long endTime = currentTime + remainingSeconds * 20;
        
        // 创建假的UUID
        String fakeUuid = "test-" + fakePlayerName.toLowerCase();
        String realUuid = player.getUuid().toString();
        
        String key = isOutgoing ? 
            realUuid + "_" + fakeUuid : 
            fakeUuid + "_" + realUuid;
        
        PVP_HOSTILITY_CACHE.put(key, endTime);
        
        String direction = isOutgoing ? "攻击" : "被攻击";
        SwordAuraLogger.log(SwordAuraLogger.LogLevel.INFO, SwordAuraLogger.Category.ATTACK,
                String.format("🧪 [测试] 添加假敌对关系 - %s %s %s (%d秒)", 
                    player.getName().getString(), direction, fakePlayerName, remainingSeconds));
    }
    
    /**
     * 清理所有敌对关系
     */
    public static void clearAllHostilities() {
        int count = PVP_HOSTILITY_CACHE.size();
        PVP_HOSTILITY_CACHE.clear();
        System.out.println("🧹 [PVP系统] 已清理所有敌对关系 (" + count + "个)");
    }
    
    /**
     * 创建测试敌对关系 - 只创建单向测试关系
     */
    public static void createTestHostilities(PlayerEntity player) {
        // 只创建单向测试敌对关系，避免UI重复显示
        addTestHostility(player, "TestPlayer1", true, 45);
        addTestHostility(player, "TestPlayer2", true, 30);
        addTestHostility(player, "TestPlayer3", true, 15);
    }
} 